package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse res=(HttpServletResponse)response;
        String uri=req.getRequestURI();
        //将获取的请求资源路径uri进行字符串切割处理
        String path=uri.substring(uri.lastIndexOf("/"));
        System.out.println(path);
        if(path.equals("/login.jsp")||path.equals("/login")){
            chain.doFilter(request, response);
            return;
        }
        //获取session对象
        HttpSession session=req.getSession();
        //进行session验证
        Object obj=session.getAttribute("name");
        if(obj==null){
            //跳转回登录页面
            request.setAttribute("result","您未登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            //res.sendRedirect("login.jsp");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }

}
